/***************************************************
 ** @Desc : This file for 用户管理
 ** @Time : 2019.04.03 9:52 
 ** @Author : Joker
 ** @File : user_manage
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.03 9:52
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"recharge/models"
	"recharge/sys"
	"recharge/utils"
	"regexp"
	"strconv"
	"strings"
)

type UserManage struct {
	KeepSession
}

var userExpandMdl = models.UserInfoExpansion{}

// 展示修改用户管理界面
// @router /user/user_manage_ui/ [get]
func (the *UserManage) ShowUserManageUI() {
	userName := the.GetSession("userName")
	if userName != nil {
		the.Data["userName"] = userName.(string)
	}

	right := the.GetSession("FilterRight")
	if right != nil {
		the.Data["right"] = right.(int)
	}

	the.TplName = "user_manage.html"
}

// 添加用户
// @router /user/add_user/?:params [post]
func (the *UserManage) AddUser() {
	uMobile := strings.TrimSpace(the.GetString("u_Mobile"))
	uName := strings.TrimSpace(the.GetString("u_Name"))
	payFee := strings.TrimSpace(the.GetString("payFee"))
	rechargeFee := strings.TrimSpace(the.GetString("rechargeFee"))
	userRate := strings.TrimSpace(the.GetString("userRate"))
	uType := the.GetString("u_Type")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	pattern := `^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$`
	matched2, _ := regexp.MatchString(pattern, payFee)
	matched3, _ := regexp.MatchString(pattern, rechargeFee)
	matched4, _ := regexp.MatchString(pattern, userRate)

	if !matched2 || !matched3 || !matched4 {
		msg = "请输入正确手续费或费率!"
	} else if uMobile == "" {
		msg = "手机号不能为空！"
	} else {

		matched, _ := regexp.MatchString(`^[1]([3-9])[0-9]{9}$`, uMobile)
		if !matched {
			msg = "请输入正确的手机号！"
		} else {
			isExit := userMdl.UserIsExit(uMobile)
			if isExit {
				msg = "该手机号已经存在！"
			} else {
				if uName == "" {
					uName = "USER_" + globalMethod.GetNowTimeV2()
				}

				u := models.UserInfo{}
				u.LoginPwd, u.Salt = globalMethod.PasswordSolt(utils.UPASSWORD)
				u.UserName = uName
				u.CreateTime = globalMethod.GetNowTime()
				u.EditTime = u.CreateTime
				u.LoginName = uMobile
				u.Mobile = uMobile
				u.Authority, _ = strconv.Atoi(uType[len(uType)-1:])

				u.PayFee, _ = globalMethod.MoneyYuanToFloat(payFee)
				u.RechargeFee, _ = globalMethod.MoneyYuanToFloat(rechargeFee)
				u.RechargeRate, _ = globalMethod.MoneyYuanToFloat(userRate)

				if u.Authority != 2 {
					u.ApiKey = globalMethod.RandomString(36)
				}

				f, id := userMdl.InsertUsers(u)
				flag = f

				// 添加IP白名单
				ux := models.UserInfoExpansion{}
				ux.CreateTime = u.CreateTime
				ux.EditTime = u.CreateTime
				ux.UserId = int(id)
				userExpandMdl.InsertUserInfoExpansion(ux)
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

// 用户列表查询分页
// @router /user/list/?:params [get]
func (the *UserManage) QueryAndListPage() {
	//分页参数
	page, _ := strconv.Atoi(the.GetString("page"))
	limit, _ := strconv.Atoi(the.GetString("limit"))
	if limit == 0 {
		limit = 20
	}

	//查询参数
	in := make(map[string]interface{})
	uName := strings.Trim(the.GetString("uName"), " ")
	uMobile := strings.Trim(the.GetString("uMobile"), " ")
	uType := the.GetString("uType")    //类型
	status := the.GetString("uStatus") //状态

	in["user_name__icontains"] = uName
	in["mobile"] = uMobile
	in["status"] = status
	if uType != "" {
		in["authority"] = uType[len(uType)-1:]
	}

	//计算分页数
	count := userMdl.SelectUserPageCount(in)
	totalPage := count / limit // 计算总页数
	if count%limit != 0 { // 不满一页的数据按一页计算
		totalPage++
	}

	//数据获取
	var list []models.UserInfo
	if page <= totalPage {
		list = userMdl.SelectUserListPage(in, limit, (page-1)*limit)
		for k := range list {
			list[k].Authority += 100
		}
	}

	//数据回显
	out := make(map[string]interface{})
	out["limit"] = limit //分页数据
	out["page"] = page
	out["totalPage"] = totalPage
	out["root"] = list //显示数据

	the.Data["json"] = out
	the.ServeJSON()
	the.StopRun()
}

//展示编辑页面
// @router /user/edit_user_ui/?:params [get]
func (the *UserManage) ShowEditUserUI() {
	editId := the.GetString(":params")
	the.SetSession("edit_Id_user", editId)

	u := userMdl.SelectOneUser(editId)
	u.Authority += 100
	userExpand := userExpandMdl.SelectOneUserInfoExpansion(u.Id)

	out := make(map[string]interface{})
	out["u"] = u
	out["ux"] = userExpand

	the.Data["json"] = globalMethod.JsonFormat(utils.SUCCESS_FLAG, out, "", "")
	the.ServeJSON()
	the.StopRun()
}

// 编辑用户
// @router /user/edit_user/?:params [post]
func (the *UserManage) EditUser() {
	uMobile := strings.TrimSpace(the.GetString("uMobile"))
	uName := strings.TrimSpace(the.GetString("uName"))
	userRate := strings.TrimSpace(the.GetString("userRate"))
	payFee := strings.TrimSpace(the.GetString("payFee"))
	rechargeFee := strings.TrimSpace(the.GetString("rechargeFee"))
	IPs := strings.TrimSpace(the.GetString("IPs"))
	uType := the.GetString("uType")

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	pattern := `^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$`
	//pattern2 := `(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})(\\.(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})){3}`
	matched2, _ := regexp.MatchString(pattern, payFee)
	matched3, _ := regexp.MatchString(pattern, rechargeFee)
	matched4, _ := regexp.MatchString(pattern, userRate)

	if !matched2 || !matched3 || !matched4 {
		msg = "请输入正确手续费或费率!"
	} else {

		matched, _ := regexp.MatchString(`^[1]([3-9])[0-9]{9}$`, uMobile)
		if !matched {
			msg = "请输入正确的手机号！"
		} else {

			//IPSplit := strings.Split(IPs, ",")
			//if IPSplit[0] != "" {
			//	matched2, _ := regexp.MatchString(pattern2, IPSplit[0])
			//	if !matched2 {
			//		msg = "请输入正确的IP！"
			//	}
			//}

			if uName == "" {
				uName = "USER_" + globalMethod.GetNowTimeV2()
			}

			editId := the.GetSession("edit_Id_user")
			if editId == nil {
				msg = "浏览器请不要禁用cookie！"
			} else {
				u := userMdl.SelectOneUser(editId.(string))
				u.Mobile = uMobile
				u.UserName = uName

				u.Authority, _ = strconv.Atoi(uType[len(uType)-1:])
				if u.Authority == 2 {
					//普通用户去掉api密钥
					u.ApiKey = ""
				}

				u.PayFee, _ = globalMethod.MoneyYuanToFloat(payFee)
				u.RechargeFee, _ = globalMethod.MoneyYuanToFloat(rechargeFee)
				u.RechargeRate, _ = globalMethod.MoneyYuanToFloat(userRate)
				u.EditTime = globalMethod.GetNowTime()

				flag = userMdl.UpdateUserInfo(u)

				ux := userExpandMdl.SelectOneUserInfoExpansion(u.Id)
				ux.EditTime = u.EditTime
				ux.Ips = IPs
				userExpandMdl.UpdateUserInfoExpansion(ux)
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

//展示加款页面
// @router /user/addition_user_ui/?:params [get]
func (the *UserManage) ShowAdditionUserUI() {
	editId := the.GetString(":params")
	the.SetSession("addition_Id_user", editId)

	u := userMdl.SelectOneUser(editId)
	u.Authority += 100

	the.Data["json"] = globalMethod.JsonFormat(utils.SUCCESS_FLAG, u, "", "")
	the.ServeJSON()
	the.StopRun()
}

// 给用户加款
// @router /user/addition_user/?:params [post]
func (the *UserManage) AdditionUser() {
	additionAmount := strings.TrimSpace(the.GetString("_amount"))

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	pattern := `^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$`
	matched2, _ := regexp.MatchString(pattern, additionAmount)

	if !matched2 {
		msg = "请输入正确金额!"
	} else {

		editId := the.GetSession("addition_Id_user")
		if editId == nil {
			msg = "浏览器请不要禁用cookie！"
		} else {
			u := userMdl.SelectOneUser(editId.(string))
			amount, _ := strconv.ParseFloat(additionAmount, 10)
			fee := amount*u.RechargeRate*0.001 + u.RechargeFee
			amount = amount - fee
			u.TotalAmount += amount
			u.UsableAmount += amount
			u.EditTime = globalMethod.GetNowTime()

			flag = userMdl.UpdateUserInfo(u)

			// 记录操作
			plusMinus := models.CustomPlusMinus{}
			plusMinus.CreateTime = u.EditTime
			plusMinus.EditTime = u.EditTime
			plusMinus.UserId = u.Id
			plusMinus.UserName = u.UserName
			plusMinus.Addition = amount
			plusMinus.HandingFee = fee
			temp, _ := PMinusMdl.InsertCustomPlusMinus(plusMinus)
			if flag > 0 && temp < 0 {
				sys.LogInfo("用户", u.UserName, "加款", amount, "成功，但是记录保存失败")
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

//展示减款页面
// @router /user/deduction_user_ui/?:params [get]
func (the *UserManage) ShowDeductionUserUI() {
	editId := the.GetString(":params")
	the.SetSession("deduction_Id_user", editId)

	u := userMdl.SelectOneUser(editId)
	u.Authority += 100

	the.Data["json"] = globalMethod.JsonFormat(utils.SUCCESS_FLAG, u, "", "")
	the.ServeJSON()
	the.StopRun()
}

// 给用户减款
// @router /user/deduction_user/?:params [post]
func (the *UserManage) DeductionUser() {
	additionAmount := strings.TrimSpace(the.GetString("deductionAmount"))

	var msg = utils.FAILED_STRING
	var flag = utils.FAILED_FLAG

	pattern := `^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$`
	matched2, _ := regexp.MatchString(pattern, additionAmount)

	if !matched2 {
		msg = "请输入正确金额!"
	} else {

		editId := the.GetSession("deduction_Id_user")
		if editId == nil {
			msg = "浏览器请不要禁用cookie！"
		} else {
			amount, _ := strconv.ParseFloat(additionAmount, 10)

			u := userMdl.SelectOneUser(editId.(string))
			if u.UsableAmount <= 0 {
				msg = "减款失败，账户余额为0"
			} else if u.UsableAmount < amount {
				msg = "减款失败，账户余额小于减款金额"
			} else {

				u.TotalAmount -= amount
				u.UsableAmount -= amount
				u.EditTime = globalMethod.GetNowTime()

				flag = userMdl.UpdateUserInfo(u)

				// 记录操作
				plusMinus := models.CustomPlusMinus{}
				plusMinus.CreateTime = u.EditTime
				plusMinus.EditTime = u.EditTime
				plusMinus.UserId = u.Id
				plusMinus.UserName = u.UserName
				plusMinus.Deduction = amount
				temp, _ := PMinusMdl.InsertCustomPlusMinus(plusMinus)
				if flag > 0 && temp < 0 {
					sys.LogInfo("用户", u.UserName, "减款", amount, "成功，但是记录保存失败")
				}
			}
		}
	}

	the.Data["json"] = globalMethod.JsonFormat(flag, "", msg, "")
	the.ServeJSON()
	the.StopRun()
}

//展示查看页面
// @router /user/look_user_ui/?:params [get]
func (the *UserManage) ShowLookUserUI() {
	editId := the.GetString(":params")
	the.SetSession("look_Id_user", editId)

	u := userMdl.SelectOneUser(editId)
	u.Authority += 100
	userExpand := userExpandMdl.SelectOneUserInfoExpansion(u.Id)

	out := make(map[string]interface{})
	out["u"] = u
	out["ux"] = userExpand

	the.Data["json"] = globalMethod.JsonFormat(utils.SUCCESS_FLAG, out, "", "")
	the.ServeJSON()
	the.StopRun()
}

// 冻结用户
// @router /user/freeze/?:params [get]
func (the *UserManage) FreezeUser() {
	delId := the.GetString(":params")

	u := userMdl.SelectOneUser(delId)
	u.Status = 1
	u.EditTime = globalMethod.GetNowTime()

	flag := userMdl.UpdateUserInfo(u)

	the.Data["json"] = globalMethod.GetDatabaseStatus(flag)
	the.ServeJSON()
	the.StopRun()
}

// 激活用户
// @router /user/active/?:params [get]
func (the *UserManage) ActiveUser() {
	delId := the.GetString(":params")

	u := userMdl.SelectOneUser(delId)
	u.Status = 0
	u.EditTime = globalMethod.GetNowTime()

	flag := userMdl.UpdateUserInfo(u)

	the.Data["json"] = globalMethod.GetDatabaseStatus(flag)
	the.ServeJSON()
	the.StopRun()
}

// 重置密码
// @router /user/reset/?:params [get]
func (the *UserManage) ResetUser() {
	delId := the.GetString(":params")

	u := userMdl.SelectOneUser(delId)
	u.LoginPwd, u.Salt = globalMethod.PasswordSolt(utils.UPASSWORD)
	u.EditTime = globalMethod.GetNowTime()

	flag := userMdl.UpdateUserInfo(u)

	the.Data["json"] = globalMethod.GetDatabaseStatus(flag)
	the.ServeJSON()
	the.StopRun()
}
